<template>
  <div class="content">
    <el-button type="primary" @click="openDialog">添加图片分类</el-button>
    <Table :dataSource="tableDate.list"></Table>

    <TypeDialog
      :form="form"
      :dialogForm="dialogForm"
      @getFormData="getFormData"
      @changeDialog="closeDialog"
      @submitForm="submitForm"
    ></TypeDialog>
  </div>
</template>

<script setup>
import api from "@/axios";
import Table from "@/components/Table.vue";
import TypeDialog from "@/components/TypeDialog.vue";
import { ref, reactive, onMounted } from "vue";
import { provide } from "@vue/runtime-core";
const dialogForm = reactive({
  title: "",
  show: false,
  formLabelWidth: "100px",
  draggable: true,
});
const tableDate = reactive({});
const tableOptions = {};
const form = reactive({
  id: "",
  tname: "",
  turl: "",
});

onMounted(() => {
  getTypeList();
});

//打开添加对话框
const openDialog = () => {
  dialogForm.title = "添加图片分类";
  dialogForm.show = true;
};

//关闭添加对话框
const closeDialog = () => {
  dialogForm.show = false;
  form.tname = "";
  form.turl = "";
  form.id = "";
};

//打开更新对话框
const openDialogWithId = (id) => {
  dialogForm.title = "更新图片分类";
  getCategoryById(id);
  dialogForm.show = true;
};
let config = {
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
};
//获取对应的blog分类
const getCategoryById = async (id) => {
  let result = await api("/ptype/get?id=" + id);
  if (result) {
    let { id, tname, turl } = result;
    form.tname = tname;
    form.turl = turl;
    form.id = id;
  }
};
//获取表单值
const getFormData = (name, val) => {
  form[name] = val;
};
//提交表单
const submitForm = () => {
  let { tname, turl, id } = form;
  if (id) {
    updateCategory(tname, turl, id);
  } else {
    addCategory(tname, turl);
  }
};
//添加分类
const addCategory = async (tname, turl) => {
  try {
  api.post("/ptype/save", { tname, turl }, config)
    ElMessage({
      message: "添加成功！",
      type: "success",
    });
    dialogForm.show = false;
    getTypeList();
  } catch (error) {
    ElMessage({
      message: "添加失败！",
      type: "error",
    });
  }
};
//更新分类
const updateCategory = async (tname, turl, id) => {
  try {
    await api.post("/ptype/update", { id, turl, tname }, config);
    ElMessage({
      message: "更新成功！",
      type: "success",
    });
    dialogForm.show = false;
    getTypeList();
  } catch (error) {
    ElMessage({
      message: "更新失败！",
      type: "error",
    });
  }
};

//获取分类信息
const getTypeList = async () => {
  try {
    let result = await api("/ptype/all");
    tableDate.list = result;
  } catch (error) {
    console.log(error);
  }
};

provide("getTypeList", getTypeList);
provide("openDialogWithId", openDialogWithId);
provide("closeDialog", closeDialog);
</script>


<style lang="scss" scoped>
</style>